<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\Common\Constants\ErrorCode;
use App\CustHub\Mapper\ChCorpMapper;
use App\Enum\WordTypeEnum;
use App\Exception\BusinessException;
use Mine\Abstracts\AbstractService;

class CommonService extends AbstractService
{
    public $mapper;

    public function __construct(ChCorpMapper $mapper)
    {
        $this->mapper = $mapper;
    }


    /**
     * 格式化消息数组
     * @param array $content
     * @return array
     */
    public static function formatMsgContent(array $content)
    {
        $newArray = [];
        $msgTypes = [];
        $types = array_keys(WordTypeEnum::getMap());
        $limit = 0;
        $firstSendTime = null;
        $secondSendTime = null;
        foreach ($content as $key => $item)
        {
            if(!in_array($item['msg_type'],$types)){
                throw new BusinessException(ErrorCode::PARAMS_ERROR,'不存在的资源类型'.$item['msg_type']);
            }
            $newItem = $item;
            if(!empty($item['extra'])){
                if(!empty($item['extra']['send_time'])){
                    if($key == 0){
                        $item['extra']['limit'] = [
                            'unit' => 2,
                            'value' => (int)$limit,
                        ];
                        $firstSendTime = new \DateTime(date("Y-m-d")." ".$item['extra']['send_time']);
                    }else{
                        $secondSendTime = new \DateTime(date("Y-m-d")." ".$item['extra']['send_time']);
                        $limit = $firstSendTime->diff($secondSendTime)->format('%i');
                        $item['extra']['limit'] = [
                            'unit' => 2,
                            'value' => (int)$limit,
                        ];
                        $firstSendTime = $secondSendTime;
                    }
                }
            }
            !empty($item['extra']) && $newItem['extra'] = $item['extra'];
            $newArray[] = $newItem;
            $msgTypes[] = $item['msg_type'];
        }
        return ['content' => $newArray,'msg_types'=>implode(",",$msgTypes)];
    }

    /**
     * 发送前转换可发送格式
     * @param array $content
     */
    public function formatBeforeSend(array $content)
    {
        return $content;
    }
}